package com.vpen.client.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * 描述
 * 基于注解@Scheduled默认为单线程，开启多个任务时，任务的执行时机会受上一个任务执行时间的影响。(串行)
 * 异步
 *
 * @author 韦鹏
 * @date 2022/11/25 11:33
 */
//@Configuration
@EnableScheduling
@EnableAsync
@Slf4j
public class ScheduleTask1 {

    /**
     * 每隔2秒执行一次
     * 默认使用 SchedulingConfigurer 配置的线程池
     */
    @Scheduled(fixedRate = 2000)
    public void taskFunc0() {
        log.debug("注解方式0：执行异步任务.....");
    }


    @Scheduled(fixedRate = 2000)
    @Async("myTaskExecutor2")
    public void taskFunc1() {
        log.debug("注解方式1：执行异步任务.....");
    }

    @Scheduled(fixedRate = 2000)
    @Async(value = "myTaskExecutor1")//指定某个线程池
    public void taskFunc2() {
        log.debug("注解方式2：执行异步任务.....");
    }

    /**
     * 配置线程池，异步定时任务
     */
    @Bean("myTaskExecutor1")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(2);
        // 设置最大线程数
        executor.setMaxPoolSize(3);
        // 设置队列容量
        executor.setQueueCapacity(10);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(10);
        // 设置默认线程名称
        executor.setThreadNamePrefix("scheduled-1-");
        // 设置拒绝策略1
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

    @Bean("myTaskExecutor2")
    public TaskExecutor taskExecutor2() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(3);
        // 设置最大线程数
        executor.setMaxPoolSize(8);
        // 设置队列容量
        executor.setQueueCapacity(10);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(10);
        // 设置默认线程名称
        executor.setThreadNamePrefix("scheduled-2-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
